package fa7.socialcode.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import fa7.socialcode.dao.ConteudoDao;
import fa7.socialcode.model.Conteudo;

public class ConteudoDaoJpa implements ConteudoDao {
	
	private static EntityManagerFactory factory;
	  static {
	    factory = Persistence.createEntityManagerFactory("socialcode");
	  }

	  private EntityManager entityManager;

	  private EntityManager getEntityManager() {
	    if (entityManager == null)
	      entityManager = factory.createEntityManager();
	    return entityManager;

	  }
	  
	  public List findConteudos(){
		  
		  return getEntityManager().createQuery("From Conteudo").getResultList();
		  
	  }
	  
	  public void removeConteudo(Conteudo conteudo) {
		    getEntityManager().getTransaction().begin();

		    getEntityManager().remove(conteudo);

		    getEntityManager().getTransaction().commit();
		  }
	  
	  public void removeConteudo(Long id) {
		    getEntityManager().getTransaction().begin();

		    getEntityManager().remove(findConteudo(id));

		    getEntityManager().getTransaction().commit();
		  }
	  public void saveConteudo(Conteudo conteudo) {
		    getEntityManager().getTransaction().begin();
		    if (conteudo.getId() != null) {
		      getEntityManager().merge(conteudo);
		    } else {
		      getEntityManager().persist(conteudo);
		    }

		    getEntityManager().getTransaction().commit();
		  }

		  public Conteudo findConteudo(Long id) {
		    return getEntityManager().find(Conteudo.class, id);
		  }

}
